<template>
  <!--我的API-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'APIPopUp'" :isShow="buttonPermissions.isAdd">
        API管理
      </pageheader>
      <div class="api-page-content">
        <el-card class="box-card tag-card">
          <span class="choice-title">所属企业：</span>
          <el-cascader
            v-model="company_id_arr"
            :placeholder="'选择所属企业'"
            collapse-tags
            :options="options"
            ref="cascaderRef"
            :props="{
              expandTrigger: 'hover',
              multiple: 'true',
              checkStrictly: 'true',
            }"
            @visible-change="companyVisibleChange"
            @change="APIChange"
            @remove-tag="APIClick"
            size="small"
            style="width:300px">
          </el-cascader>
          <el-table :data="tableData" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="所属集团" prop="company_name" align="center" width="120"></el-table-column>
            <el-table-column label="api_key" prop="api_key" align="center" ></el-table-column>
            <el-table-column label="api_secret" prop="api_secret" align="center" width="460">
              <template slot-scope="scope">
                <span v-show="scope.row.isShowAPISecret">{{scope.row.api_secret}}</span>
                <span v-show="!scope.row.isShowAPISecret">***********</span>
                <el-button size="mini" @click="scope.row.isShowAPISecret = !scope.row.isShowAPISecret" style="margin-left: 20px">
                  <span v-show="scope.row.isShowAPISecret">隐藏</span>
                  <span v-show="!scope.row.isShowAPISecret">显示</span>
                </el-button>
                <el-button size="mini" @click="refreshSecret(scope.row.id)" style="margin-left: 20px">更新密钥</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="280">
              <template slot-scope="scope">
                <el-button v-if="scope.row.is_use" @click="APISetUse(scope.row)" type="primary" size="small">禁用</el-button>
                <el-button v-else @click="APISetUse(scope.row)" size="small">启用</el-button>
                <el-button @click="APIData(scope.row)" size="small">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog v-dialogDrag :title="pageTitle" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="所属企业" prop="company_id_arr">
              <Cascader v-if="!isDisabled"
                :value.sync="ruleForm.company_id_arr"
                        :options="options"
                        :changeEvent="'companyChange'"
                        :width="'450px'"
                        :disabled="isDisabled"
                        :isClearable="false"></Cascader>
              <el-input v-else v-model="ruleForm.company_name" disabled size="small" style="width:450px;"></el-input>
            </el-form-item>
            <el-form-item label="时间粒度" prop="interval_list">
              <el-select v-model="ruleForm.interval_list" @visible-change="intervalVisibleChange"  filterable
                         multiple size="small" collapse-tags placeholder="请选择时间粒度" style="width:450px;">
                <el-option v-for="item in allIntervalList" :key="item.tag" :label="item.name" :value="item.tag"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="指标粒度" prop="indicator_list">
              <el-select v-model="ruleForm.indicator_list" @visible-change="indicatorVisibleChange"  filterable
                         multiple size="small" collapse-tags placeholder="请选择指标" style="width:450px;">
                <el-option v-for="item in indicator_list" :key="item.key" :label="item.name" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="isDisabled" label="api_key" prop="api_key">
              <el-input v-model="ruleForm.api_key" disabled size="small" style="width:450px;"></el-input>
            </el-form-item>
            <el-form-item v-if="isDisabled" label="api_secret" prop="api_secret">
              <el-input v-model="ruleForm.api_secret" disabled size="small" style="width:450px;"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss" scoped>
  .api-page-content{
    padding: 15px;
    .tag-card{
      border: none;
      border-radius: 0;
      &.is-always-shadow{
        box-shadow: none;
      }
      .el-card__body{
        padding: 0 35px 35px 35px !important;
        .el-table{
          .el-table__header-wrapper{
            .has-gutter{
              tr{
                th{
                  background:#f5f6fa;
                  color:#212947;
                  font-weight: 400;
                  line-height: 56px;
                  padding-top: 0;
                  padding-bottom: 0;
                }
              }
            }
          }


          .el-table__body{
            tbody{
              .el-table__row{
                td{
                  line-height: 50px;
                  height: 50px;
                  div{
                    line-height: 25px;
                  }
                  padding: 0;
                }
              }
              .el-table__row--striped{
                &:hover{
                  &>td{
                    background-color: #F5F7FA;
                  }
                }
                td{
                  background: #f9fafe;
                }
              }
            }
          }
        }
      }
    }
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .company-card{
      width: 80%;
      margin-top: 20px;
      ul{
        li{
          padding: 5px;
          .company-card-tit{
            display: inline-block;
            width: 120px;
          }
        }
      }
      .remarks{
        font-size: 14px;
        color: #828282;
        font-style: italic;
      }
    }
    .el-table{
      .el-table__body-wrapper{
        .el-table__body{
          .el-table__row{
            cursor: pointer;
            &.current-row{
              .is-center{
                &:first-child{
                  &::after{
                    border: 2px solid #6689f1;
                  }
                  &::before{
                    content: '';
                    display: block;
                    width:6px;
                    height: 6px;
                    border-radius: 50%;
                    background:#6689f1;
                    position: absolute;
                    top:50%;
                    transform: translateY(-50%);
                    left:24px;

                  }
                }
              }
            }
            .is-center{
              &:first-child{
                position: relative;
                &::after{
                  content: '';
                  display: block;
                  width:10px;
                  height:10px;
                  border: 2px solid #ccc;
                  border-radius:50%;
                  position: absolute;
                  left:20px;
                  top:50%;
                  transform: translateY(-50%);

                }
              }

            }
          }
        }
      }
    }
  }
</style>
<script>
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";
  function $(id) { return document.getElementById(id); }

  export default {
    data() {
      return {
        isDisabled:false,//是否是修改状态
        isShow:false,//是否显示普通模态框
        pageTitle:'新增API账号',//模态框名称
        company_id:'',//所属企业选中id
        company_id_arr:[],//所属企业选中id arr
        options:[],//级联控件 所属企业
        allIntervalList:[],//全部合法时间粒度list
        indicator_list:[],//获取指标list
        tableData:[],//表格参数
        pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },//表格分页参数
        ruleForm: {
          company_id_arr: [],//所属企业arr
          company_id: '',//所属企业str
          company_name: '',//所属企业名称
          indicator_list: [],//指标list
          interval_list: [],//时间粒度list
          api_key:'',
          api_secret:'',
          id:'',
        },//普通角色模态框form表单
        rules: {
          company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
          indicator_list: [{ required: true, message: "请选择指标",trigger:'change'}],
          interval_list: [{ required: true, message: "请选择时间粒度",trigger:'change'}],
        },//普通角色form表单验证
        buttonPermissions:{
          isAdd:false,
          isDel:false,
          isBaseModify:false,
          isOpModify:false,
          isWatch:false,
        },
      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      Cascader
    },
    created() {
      //判断是否有按钮权限
      if(sessionStorage.buttonPermissions){
        this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
      }
      //初始化
      this.getTree();
      this.getAllIntervalList()
    },
    mounted() {
      //新增按钮点击事件
      this.$Bus.$on("APIPopUp", () => {
        this.isShow = true;
        this.isDisabled = false;
        this.pageTitle = '新增API账号'
      });
      //所属企业change事件
      this.$Bus.$on("APIChange", data => {
        this.company_id = data.slice(-1)[0];
        this.$Bus.$emit('Loading',false)
      });
      //添加和修改中选择所属企业change事件
      this.$Bus.$on('companyChange',data =>{
        if(data.length){
          this.ruleForm.company_id_arr = data
          this.ruleForm.company_id = data.slice(-1)[0]
          this.ruleForm.indicator_list = []
          this.getIndicatorList()
        }
        this.$nextTick(()=>{
          this.$refs.ruleForm.validateField('company_id_arr');//触发form表单中校验所属企业是否选择
        })

      })
    },
    beforeDestroy(){
      //销毁Bus绑定事件
      this.$Bus.$off('APIPopUp')
    },
    methods: {
      //配置按钮权限，根据权限不同调整表头渲染参数
      configPermissions(val){
        let buttonPermissions = val
        let menuButtonPermissions = [];//按钮权限数组
        buttonPermissions.forEach(e =>{
          for(let key in e){
            if(key == 'menu_code'){
              menuButtonPermissions.push(e[key])
            }
          }
        });
        this.buttonPermissions.isAdd = menuButtonPermissions.includes('mallAdd') ? true : false; //是否有新增权限
        this.buttonPermissions.isDel = menuButtonPermissions.includes('mallDelete') ? true : false; //是否有删除权限
        this.buttonPermissions.isBaseModify = menuButtonPermissions.includes('mallBaseModify') ? true : false; //是否有基础修改权限
        this.buttonPermissions.isOpModify = menuButtonPermissions.includes('mallOpModify') ? true : false; //是否有运维修改权限
        this.buttonPermissions.isWatch = menuButtonPermissions.includes('mallWatch') ? true : false; //是否有查看权限

      },
      //获取企业tree
      getTree(){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            this.options = data.data
            this.company_id_arr.push([data.data[0].id])
            this.company_id = data.data[0].id
            this.getList()
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //获取全部合法的时间粒度
      getAllIntervalList(){
        let url = 'sys/report_assist_new/all_interval_list'
        this.$api.post(url)
        .then(data=>{
          if(data){
            this.allIntervalList = data.data
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //表格序号显示方法
      indexMethod(index){
        return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
      },
      //获取表格List数据
      getList(){
        if(this.company_id_arr.length == 0){
          this.defaultData()
          return
        }
        let id = this.company_id_arr.map(x=>x.slice(-1)[0])
        // console.log(id,'id');
        let url = '/sys/api-manager/search?company_id_list='+ id + '&page=' + this.pagination.currentPage + '&page_size=' + this.pagination.pageSize
        this.$api.post(url)
        .then(data=>{
          // console.log(data,'data');
          if(data && data.data){
            let _data = data.data
            this.tableData = _data.dataList.map(x=>{
              x.isShowAPISecret = false
              return x
            })
            this.pagination.total = _data.dataCount;
            this.pagination.currentPage = _data.pageCode;
            this.pagination.pageSize = _data.pageSize;
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.defaultData()
          this.$Bus.$emit('Loading',false);
        })
      },
      defaultData(){
        this.tableData = [];
        this.pagination.total = 0
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
      },
      //所属企业change事件
      companyVisibleChange(val){
        if(!val){
          this.pagination.currentPage =1
          this.getList()
        }
      },
      APIChange(val){
        if(val.length == 0){
          this.$message.warning('请至少选择一个企业!');
        }
      },
      APIClick(val){
        if(this.company_id_arr.length==0) {
          this.$message.warning('请至少选择一个企业!');
        }
        this.pagination.currentPage =1
        this.$nextTick(()=>{
          this.getList(this.company_id)
        })
      },
      //更新密钥
      refreshSecret(id){
        this.$confirm("是否更新密钥？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          this.$Bus.$emit('Loading', true);
          let url = '/sys/api-manager/refresh_secret?id=' + id
          this.$api.post(url)
          .then(data => {
            console.log(data);
            if (data) {
              this.$message.success('更新成功')
              this.getList()
            } else {
              this.$Bus.$emit('Loading', false);
            }

          })
          .catch(err => {
             console.log(err);
            this.$Bus.$emit('Loading', false);
          })
        })
        .catch(() => {
        });
      },
      //分页change事件
      currentChange(){
        if(this.company_id_arr.length==0) {
          this.$message.warning('请至少选择一个企业!');
          return
        }
        this.$Bus.$emit('Loading',true)
        this.getList(this.company_id)
      },
      //每页显示条目个数change事件
      sizeChange(){
        if(this.company_id_arr.length==0) {
          this.$message.warning('请至少选择一个企业!');
          return
        }
        this.$Bus.$emit('Loading',true)
        this.getList(this.company_id)
      },
      //点击启用禁用按钮
      APISetUse(data){
        let msg = data.is_use ? "是否禁用‘"+ data.company_name +"’？ " :  "是否启用‘"+ data.company_name +"’？ "
        this.$confirm(msg,{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center:true
        })
        .then(() => {
          this.$Bus.$emit('Loading',true)
          this.setUse(data.id,data.is_use)
        })
        .catch(() => {

        });
      },
      //调用启用禁用接口
      setUse(id,is_use){
        is_use = is_use ? 0 : 1
        let url = 'sys/api-manager/set_enable?id=' + id +'&is_use='+ is_use;
        this.$api.post(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }

          if(data){
            this.getList();
            this.$message({
              message: "修改成功",
              type: "success"
            });
          }else{
            this.$Bus.$emit('Loading',false)
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //点击详情按钮
      APIData(data){
        this.isDisabled = true
        this.isShow = true;
        this.pageTitle = '修改API账号'
        this.ruleForm.company_id = data.company_id
        this.getIndicatorList()
        this.getApiManager(data.id)
      },
      //调用获取用户详情接口
      getApiManager(id){
        let url = '/sys/api-manager/get?id='+ id
        this.$api.post(url)
        .then(data=>{
          if(data){
            console.log(data);
            let _data = data.data
            this.ruleForm.company_name = _data.company_name
            this.ruleForm.indicator_list = _data.indicator_vo_list.map(x=>x.key)
            this.ruleForm.interval_list = _data.interval_vo_list.map(x=>x.tag)
            this.ruleForm.api_key = _data.api_key
            this.ruleForm.api_secret = _data.api_secret
            this.ruleForm.id = _data.id
            this.ruleForm.company_id_arr = [_data.id]
            console.log(this.ruleForm,'ruleForm');
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },

      //时间粒度change事件
      intervalVisibleChange(val){
        this.$refs.ruleForm.validateField('interval_list')
      },
      //获取指标粒度list
      getIndicatorList(){
        let url = 'sys/report_assist_new/get_indicator_list'
        let params = {
          org_id_list: Array.of(this.ruleForm.company_id),
          org_type: 1
        }
        console.log(params,'params');
        this.$api.post(url,params)
        .then(data=>{
          console.log(data);
          if(data && data.data){
            this.indicator_list = data.data
          }else{
            this.indicator_list = []
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.indicator_list = []
          this.ruleForm.indicator_list = []
          this.$Bus.$emit('Loading',false)
        })
      },
      //指标change事件
      indicatorVisibleChange(){
        this.$refs.ruleForm.validateField('indicator_list')
      },
      //保存按钮
      confirmDialog(formName){
        let data = {};
        let model = null
        let url = ''
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading',true)
            model = this.$refs[formName].model;
            //判断模态框开启状态 true：修改：false：新增
            if(this.isDisabled){
              url = '/sys/api-manager/update_api?id='+ this.ruleForm.id
              data.indicator_list = model.indicator_list
              data.interval_list = model.interval_list
              this.apiUpdata(url,data)
            }else{
              url = '/sys/api-manager/create_api'
              data.company_id = model.company_id
              data.indicator_list = model.indicator_list
              data.interval_list = model.interval_list
              this.apiAdd(url,data)
            }
          } else {
            console.log("error submit!!");
            return;
          }
        });
      },
      //新增
      apiAdd(url,params){
        this.$api.post(url,params)
        .then(data=>{
          console.log(data);
          if(data){
            this.isShow = false;
            this.getList()
            this.$message({
              message: "新增成功",
              type: "success"
            });
          }else{
            this.$Bus.$emit('Loading',false)
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },

      //修改
      apiUpdata(url,params){
        this.$api.post(url,params)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            this.isShow = false;
            this.getList()
            this.$message({
              message: "修改成功",
              type: "success"
            });
          }else{
            this.$Bus.$emit('Loading',false)
          }
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //关闭模态框
      closeDialog(formName){
        this.indicator_list = []
        this.ruleForm.id = '';
        this.ruleForm.company_name = '';
        this.$refs[formName].resetFields();
        this.$Bus.$emit('Loading',false)
      },
      copy(id){
        let obj = document.getElementById(id)
        obj.select();
        document.execCommand("Copy")
        this.$message.success('复制成功')
      },
    },
    watch: {}
  }
</script>
